<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
			<el-form-item label="医生姓名" prop="doctorName">
				<el-input
					v-model="queryParams.doctorName"
					placeholder="请输入医生姓名"
					clearable
					size="small"
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="手机号" prop="phone">
				<el-input
					v-model="queryParams.phone"
					placeholder="请输入手机号"
					clearable
					size="small"
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="身份证" prop="idCard">
				<el-input
					v-model="queryParams.idCard"
					placeholder="请输入身份证"
					clearable
					size="small"
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="任务时间" prop="taskTime">
				<el-date-picker clearable size="small" style="width: 200px"
								v-model="queryParams.taskTime"
								type="date"
								value-format="yyyy-MM-dd"
								placeholder="选择任务时间">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="审核状态" prop="auditStatus">
				<el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable size="small">
					<el-option v-for="(item, index) in statusOptions" :key="index"
							   :label="item.dictLabel" :value="item.dictValue"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button
					type="primary"
					icon="el-icon-plus"
					size="mini"
					@click="handleAdd"
				>新增
				</el-button>
			</el-col>
<!--			<el-col :span="1.5">
				<el-button
					type="success"
					icon="el-icon-edit"
					size="mini"
					:disabled="single"
					@click="handleUpdate"
				>修改
				</el-button>
			</el-col>-->
			<el-col :span="1.5">
				<el-button
					type="danger"
					icon="el-icon-delete"
					size="mini"
					:disabled="multiple"
					@click="handleDelete"
				>删除
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="warning"
					icon="el-icon-download"
					size="mini"
					@click="handleExport"
				>导出
				</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="voucherList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center"/>
			<el-table-column type="index" fixed :index="indexMethod" label="序号" width="55" align="center"/>
			<el-table-column label="医生姓名" fixed align="center" width="100" :show-overflow-tooltip="true"
							 prop="doctorName"/>
			<el-table-column label="手机号" align="center" width="120" :show-overflow-tooltip="true" prop="phone"/>
			<el-table-column label="身份证" align="center" width="180" :show-overflow-tooltip="true" prop="idCard"/>
			<el-table-column label="服务分类" align="center" width="250" :show-overflow-tooltip="true" prop="catalog"/>
			<el-table-column label="服务项目" align="center" width="100" :show-overflow-tooltip="true" prop="project"/>
			<el-table-column label="服务分级" align="center" width="100" :show-overflow-tooltip="true">
				<template slot-scope="scope">
					<span v-if="!scope.row.classify">-</span>
					<span v-else>{{scope.row.classify}}</span>
				</template>
			</el-table-column>
			<el-table-column label="服务积分" align="center" width="100" :show-overflow-tooltip="true" prop="point"/>
			<el-table-column label="任务描述" align="center" width="250" :show-overflow-tooltip="true" prop="description"/>
			<el-table-column label="任务时间" align="center" width="100" :show-overflow-tooltip="true">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.taskTime, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="审核状态" fixed="right" align="center" :show-overflow-tooltip="true">
				<template slot-scope="scope">
					<span v-if="scope.row.finalStatus!=null">{{ scope.row.finalStatus == 0 ? '审核通过' : '终审未通过' }}</span>
					<span
						v-else-if="scope.row.reviewStatus!=null">{{ scope.row.reviewStatus == 0 ? '待终审' : '复审未通过' }}</span>
					<span
						v-else-if="scope.row.auditStatus!=null">{{ scope.row.auditStatus == 0 ? '待复审' : '初审未通过' }}</span>
					<span v-else>待初审</span>
				</template>
			</el-table-column>
			<el-table-column label="初审人" align="center" width="100" :show-overflow-tooltip="true" prop="auditUser"/>
			<el-table-column label="初审时间" align="center" width="150" :show-overflow-tooltip="true">
				<template slot-scope="scope">
					<span>{{ scope.row.auditTime }}</span>
				</template>
			</el-table-column>
			<el-table-column label="复审人" align="center" width="100" :show-overflow-tooltip="true" prop="reviewUser"/>
			<el-table-column label="复审时间" align="center" width="150" :show-overflow-tooltip="true">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.reviewTime) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="终审人" align="center" width="100" :show-overflow-tooltip="true" prop="finalUser"/>
			<el-table-column label="终审时间" align="center" width="150" :show-overflow-tooltip="true">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.finalTime) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" fixed="right" width="100">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.auditStatus==null"
							   @click="handleUpdate(scope.row, 'auditStatus')">
						初审
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-edit" v-else-if="scope.row.auditStatus!=null&&scope.row.reviewStatus==null"
							   @click="handleUpdate(scope.row, 'reviewStatus')">
						复审
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-edit"
							   v-else-if="scope.row.auditStatus!=null&&scope.row.reviewStatus!=null&&scope.row.finalStatus==null"
							   @click="handleUpdate(scope.row, 'finalStatus')">
						终审
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-edit"
							   v-else @click="handleUpdate(scope.row, 'showView')">
						查看
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination
			v-show="total>0"
			:total="total"
			:page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize"
			@pagination="getList"
		/>

		<!-- 添加或修改任务凭证对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="70%" append-to-body @close="handleCloseDialog">
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-row :gutter="10">
					<el-col :span="24">
						<el-form-item label="医生姓名" prop="doctorName">
							<el-autocomplete popper-class="my-autocomplete" v-model="form.doctorName"
											 :fetch-suggestions="querySearchAsync"
											 style="width: 100%;" :disabled="form.voucherId!=null" placeholder="点击选择医生"
											 @select="handleSelect" @clear="handleClear" clearable>
								<i class="el-icon-edit el-input__icon" slot="suffix"></i>
								<template slot-scope="{ item }">
									<div class="name">{{ item.doctorName }}</div>
									<span class="hospitalName">{{ item.hospitalName }}</span>
								</template>
							</el-autocomplete>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="手机号" prop="phone">
							<el-input v-model="form.phone" placeholder="请输入手机号" :disabled="true"/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="身份证" prop="idCard">
							<el-input v-model="form.idCard" placeholder="请输入身份证" :disabled="true"/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="任务类型" prop="catalog">
							<el-cascader ref="cascader" :props="{label: 'serviceName', value: 'serviceName'}"
										 v-model="taskType" :disabled="form.voucherId!=null" :options="taskTypeOptions"
										 @change="handleCascaderChange" style="width: 100%" clearable></el-cascader>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="任务积分" prop="point">
							<el-input-number v-model="form.point" :precision="0" :step="1" placeholder="请输入任务积分"
											 style="width: 100%;"/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="任务时间" prop="taskTime">
							<el-date-picker clearable style="width: 100%" value-format="yyyy-MM-dd"
											:disabled="form.voucherId!=null" v-model="form.taskTime" type="date"
											placeholder="选择任务时间">
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="任务描述" prop="description">
							<el-input type="textarea" :rows="3" :disabled="form.voucherId!=null"
									  v-model="form.description" placeholder="请输入任务描述"/>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="任务图片" prop="taskImage">
							<el-upload
								ref="upload"
								:action="upload.url"
								:headers="upload.headers"
								list-type="picture-card"
								:limit="5"
								:disabled="form.voucherId!=null"
								:file-list="fileList"
								:on-success="handleUploadSuccess"
								:before-upload="beforeUpload"
								:on-preview="handlePictureCardPreview"
								:on-remove="handleRemove">
								<i class="el-icon-plus"></i>
							</el-upload>
						</el-form-item>
					</el-col>
					<el-col :span="24" v-if="statusKey">
						<el-form-item label="审核状态">
							<el-timeline>
								<el-timeline-item size="large" v-if="form.auditStatus != null && form.reviewStatus != null">
									<span :class="[form.finalStatus == 0 ? 'timeline-main-success' : form.finalStatus == 1 ? 'timeline-main-error' : 'timeline-main-await']">
										终审 {{ form.finalStatus == 0 ? '通过' : form.finalStatus == 1 ? '未通过' : '待终审' }}
								    </span>
									<span class="timeline-sub" v-if="form.finalTime">
										{{ form.finalTime }}
									</span>
									<p v-if="form.finalStatus!=null&&form.finalComment">{{ form.finalUser }}：{{ form.finalComment }}</p>
								</el-timeline-item>
								<el-timeline-item size="large" v-if="form.auditStatus != null">
									<span :class="[form.reviewStatus == 0 ? 'timeline-main-success' : form.reviewStatus == 1 ? 'timeline-main-error' : 'timeline-main-await']">
										复审 {{ form.reviewStatus == 0 ? '通过' : form.reviewStatus == 1 ? '未通过' : '待复审' }}
								    </span>
									<span class="timeline-sub" v-if="form.reviewTime">
										{{ form.reviewTime }}
									</span>
									<p v-if="form.reviewStatus!=null&&form.reviewComment">{{ form.reviewUser }}：{{ form.reviewComment }}</p>
								</el-timeline-item>
								<el-timeline-item size="large">
									<span :class="[form.auditStatus == 0 ? 'timeline-main-success' : form.auditStatus == 1 ? 'timeline-main-error' : 'timeline-main-await']">
										初审 {{ form.auditStatus == 0 ? '通过' : form.auditStatus == 1 ? '未通过' : '待初审' }}
								    </span>
									<span class="timeline-sub">
										{{ form.auditStatus != null ? form.auditTime : form.createTime }}
									</span>
									<p v-if="form.auditStatus!=null&&form.auditComment">{{ form.auditUser }}：{{ form.auditComment }}</p>
								</el-timeline-item>
							</el-timeline>
						</el-form-item>
					</el-col>
					<el-col :span="24" v-if="statusKey && statusKey != 'showView'">
						<el-form-item label="审核意见" prop="auditComment">
							<el-input v-if="statusKey=='auditStatus'" type="textarea" :rows="3"
									  v-model="form.auditComment" placeholder="请输入审核意见"/>
							<el-input v-if="statusKey=='reviewStatus'" type="textarea" :rows="3"
									  v-model="form.reviewComment" placeholder="请输入审核意见"/>
							<el-input v-if="statusKey=='finalStatus'" type="textarea" :rows="3"
									  v-model="form.finalComment" placeholder="请输入审核意见"/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<template v-if="statusKey && statusKey != 'showView'">
					<el-button type="primary" @click="submitForm(0)">审核通过</el-button>
					<el-button @click="submitForm(1)">审核不通过</el-button>
				</template>
				<template v-if="!statusKey">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</template>
			</div>
		</el-dialog>
		<el-dialog :visible.sync="dialogVisible">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>
	</div>
</template>

<script>
import {listVoucher, getVoucher, delVoucher, addVoucher, updateVoucher, exportVoucher} from "@/api/sunshine/voucher";
import {getAllDoctor} from '@/api/doctor'
import {getToken} from "@/utils/auth";
import {listService} from "@/api/hospital/service";
import {addPoint} from "@/api/point/point";

export default {
	name: "Voucher",
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 任务凭证表格数据
			voucherList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				doctorId: null,
				doctorName: null,
				phone: null,
				idCard: null,
				catalog: null,
				project: null,
				classify: null,
				description: null,
				taskImage: null,
				taskTime: null,
				auditStatus: null,
				auditComment: null,
				orderByColumn: 'create_time',
				isAsc: 'desc'
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				doctorName: [
					{required: true, message: "请选择医生", trigger: "change"}
				],
				// phone: [
				// 	{required: true, message: "请填写手机号", trigger: "blur"}
				// ],
				idCard: [
					{required: true, message: "请填写身份证号码", trigger: "blur"}
				],
				catalog: [
					{required: true, message: "请选择任务类型", trigger: "change"}
				],
				taskTime: [
					{required: true, message: "请选择任务时间", trigger: "change"}
				],
				description: [
					{required: true, message: "请填写任务描述", trigger: "blur"}
				],
				taskImage: [
					{required: true, message: "请上传任务图片", trigger: "change"}
				],
				auditStatus: [
					{required: true, message: "请选择审核状态", trigger: "change"}
				],
				point: [
					{required: true, message: "请填写任务积分", trigger: "change"}
				]
			},
			statusOptions: [],
			titleOptions: [],
			restaurants: [],
			dialogImageUrl: '',
			dialogVisible: false,
			upload: {
				// 是否禁用上传
				isUploading: false,
				// 设置上传的请求头部
				headers: {Authorization: "Bearer " + getToken()},
				// 上传的地址
				url: process.env.VUE_APP_BASE_API + "/uploadOssFile",
			},
			taskImages: [],
			taskType: [],
			fileList: [],
			taskTypeOptions: [],
			statusKey: undefined,
			ossUrl: this.$ossUrl
		};
	},
	created() {
		this.getList();
		this.getDicts('voucher_audit_status').then(res => {
			this.statusOptions = res.data;
		})
	},
	mounted() {
		this.getAllDoctor();
		this.getServiceList();
	},
	methods: {
		/** 查询任务凭证列表 */
		getList() {
			this.loading = true;
			listVoucher(this.queryParams).then(response => {
				this.voucherList = response.rows;
				this.total = response.total;
				this.loading = false;
			});
		},
		getAllDoctor() {
			getAllDoctor().then(res => {
				this.restaurants = res.data;
			})
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				voucherId: null,
				doctorId: null,
				doctorName: null,
				phone: null,
				idCard: null,
				catalog: null,
				project: null,
				classify: null,
				point: null,
				description: null,
				taskImage: null,
				taskTime: null,
				auditStatus: null,
				auditUser: null,
				auditTime: null,
				auditComment: null,
				reviewStatus: null,
				reviewUser: null,
				reviewTime: null,
				reviewComment: null,
				finalStatus: null,
				finalUser: null,
				finalTime: null,
				finalComment: null,
				createTime: null,
				createBy: null,
				updateTime: null,
				updateBy: null
			};
			this.resetForm("form");
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm");
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.voucherId)
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.title = "添加任务凭证";
			this.statusKey = undefined;
		},
		/** 修改按钮操作 */
		handleUpdate(row, status) {
			this.statusKey = status;
			this.reset();
			const voucherId = row.voucherId || this.ids
			getVoucher(voucherId).then(response => {
				this.form = response.data;
				if(this.form.catalog) {
					this.taskType.push(this.form.catalog);
				}
				if(this.form.project) {
					this.taskType.push(this.form.project);
				}
				if(this.form.classify) {
					this.taskType.push(this.form.classify);
				}
				if (this.form.taskImage) {
					let imageList = this.form.taskImage.split(',');
					for (let i = 0; i < imageList.length; i++) {
						this.taskImages.push(imageList[i]);
						this.fileList.push({url: this.ossUrl + imageList[i]});
					}
				}
				this.open = true;
				this.title = "修改任务凭证";
			});
		},
		/** 提交按钮 */
		submitForm(status) {
			this.$refs["form"].validate(valid => {
				if (valid) {
					if(status != undefined) {
						this.form[this.statusKey] = status;
					}
					let temp = { ...this.form };
					if (status == 0) {
						temp["auditStatus"] = 0;
						temp["reviewStatus"] = 0;
						temp["finalStatus"] = 0;
						temp["reviewComment"] = temp["auditComment"];
						temp["finalComment"] = temp["auditComment"];
					}
					console.log(temp);
					if (this.form.voucherId != null) {
						updateVoucher(temp).then(response => {
							if (response.code === 200) {
								this.msgSuccess("修改成功");
								this.open = false;
								this.getList();
								// if(this.statusKey == 'finalStatus') {
									let params = {
										pointEventName: this.form.catalog + this.form.classify + this.form.project ? this.form.project: '',
										pointEventValue: this.form.point,
										isPlus: 0,
										doctorId: this.form.doctorId
									}
									addPoint(params);
								// }
							}
						});
					} else {
						addVoucher(this.form).then(response => {
							if (response.code === 200) {
								this.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							}
						});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const voucherIds = row.voucherId || this.ids;
			this.$confirm('是否确认删除任务凭证编号为"' + voucherIds + '"的数据项?', "警告", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(function () {
				return delVoucher(voucherIds);
			}).then(() => {
				this.getList();
				this.msgSuccess("删除成功");
			}).catch(function () {
			});
		},
		/** 导出按钮操作 */
		handleExport() {
			const queryParams = this.queryParams;
			this.$confirm('是否确认导出所有任务凭证数据项?', "警告", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(function () {
				return exportVoucher(queryParams);
			}).then(response => {
				this.download(response.msg);
			});
		},
		statusFormat(value, options) {
			return this.selectDictLabel(options, value);
		},
		querySearchAsync(queryString, cb) {
			let restaurants = this.restaurants;
			let results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
			cb(results);
		},
		createStateFilter(queryString) {
			return (state) => {
				return (state.doctorName && state.doctorName.indexOf(queryString) === 0);
			};
		},
		handleSelect(item) {
			this.form.doctorId = item.doctorId;
			this.form.doctorName = item.doctorName;
			this.form.phone = item.phone;
			this.form.idCard = item.idCard;
			this.$refs.form.validateField('phone');
			this.$refs.form.validateField('idCard');
		},
		handleClear() {
			this.form.doctorId = undefined;
			this.form.phone = undefined;
			this.form.idCard = undefined;
		},
		handleRemove(file, fileList) {
			let target = file.response ? file.response.fileName : file.url.replace(this.ossUrl, '');
			let index = this.taskImages.indexOf(target);
			this.taskImages.splice(index, 1);
			this.form.taskImage = this.taskImages.join(',');
		},
		handlePictureCardPreview(file) {
			this.dialogImageUrl = file.url;
			this.dialogVisible = true;
		},
		handleUploadSuccess(res) {
			this.taskImages.push(res.fileName);
			this.form.taskImage = this.taskImages.join(',');
			this.$refs.form.validateField('taskImage');
		},
		beforeUpload(file) {
			let fileType = file.type;
			if (fileType === 'image/jpeg' || fileType === 'image/png') {
				return true;
			} else {
				this.$message.error('请插入图片类型文件(jpg/jpeg/png)');
				return false;
			}
		},
		handleCascaderChange(value) {
			let nodeContent = this.$refs["cascader"].getCheckedNodes()[0].data;
			if (nodeContent.point > 0) {
				this.form.point = nodeContent.point;
			}
			this.form.catalog = value[0];
			this.form.project = value[1];
			this.form.classify = value[2];
		},
		getPreviewTaskImage(taskImage) {
			if (taskImage) {
				return this.ossUrl + taskImage.split(',')[0];
			}
		},
		getPreviewTaskImageList(taskImage) {
			let previewList = [];
			if (taskImage) {
				let imageList = taskImage.split(',');
				for (let i = 0; i < imageList.length; i++) {
					previewList.push(this.ossUrl + imageList[i]);
				}
			}
			return previewList;
		},
		indexMethod(index) {
			return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
		},
		handleCloseDialog() {
			this.fileList = [];
			this.taskImages = [];
			this.taskType = [];
		},
		getServiceList() {
			listService().then(response => {
				this.taskTypeOptions = this.handleTreeData(response.data, "serviceId", "parentId");
			});
		}
	}
};
</script>
<style lang="less" scoped>
.my-autocomplete {
	li {
		line-height: normal;
		padding: 7px;

		.name {
			text-overflow: ellipsis;
			overflow: hidden;
		}

		.hospitalName {
			font-size: 12px;
			color: #b4b4b4;
		}

		.highlighted .addr {
			color: #ddd;
		}
	}
}

::v-deep .el-timeline {
	padding-left: 0;
}
.timeline-main-success {
	color: #67C23A;
	font-size: 16px;
	font-weight: bold;
}

.timeline-main-error {
	color: #F56C6C;
	font-size: 16px;
	font-weight: bold;
}

.timeline-main-await {
	color: #909399;
	font-size: 16px;
	font-weight: bold;
}

.timeline-sub {
	color: #7F7F7F;
	margin-left: 10%;
}
</style>
